<template>
  <div class="department-container">
    <div class="app-container">
      <el-card>
        <!-- 用一个行列布局 -->
        <el-row type="flex" justify="space-between" align="middle" style="height: 40px">
          <el-col :span="20">
            <span>康保县旭日东升有限公司</span>
          </el-col>
          <el-col :span="4">
            <el-row type="flex" justify="end">
              <!-- 两个内容 -->
              <el-col>负责人</el-col>
              <el-col>操作</el-col>
            </el-row>
          </el-col>
        </el-row>
        <!-- 树状结构 -->
        <el-tree :data="list" :props="defaultProps" :default-expand-all="true">
          <template #default="{ data }">
            <!-- 插槽 -->
            <el-row type="flex" justify="space-between" align="middle" style="height: 40px; width: 100%">
              <el-col :span="20">
                <span>{{ data.name }}</span>
              </el-col>
              <el-col :span="4">
                <el-row type="flex" justify="end">
                  <!-- 两个内容 -->
                  <el-col>{{ data.manager }}</el-col>
                  <el-col>
                    <!-- 下拉菜单 element -->
                    <el-dropdown>
                      <span> 操作<i class="el-icon-arrow-down" /> </span>
                      <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item @click.native="openAddDep(data.id,'添加部门')">添加子部门</el-dropdown-item>
                        <el-dropdown-item @click.native="openUpdataDep(data.id,'编辑部门')">编辑部门</el-dropdown-item>
                        <el-dropdown-item @click.native="delDep(data.id)">删除部门</el-dropdown-item>
                      </el-dropdown-menu>
                    </el-dropdown>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-tree>
      </el-card>
    </div>
    <!-- 添加部门的弹窗 -->
    <el-dialog :title="title" :visible="dialogVisible" width="30%" @close="closeDialog" @open="openDialog">
      <template>
        <el-form ref="addfrom" label-width="120px" :model="from" :rules="rules">
          <el-form-item label="部门名称" prop="name">
            <el-input v-model="from.name" style="width: 80%" placeholder="1-50个字符" />
          </el-form-item>
          <el-form-item label="部门编码" prop="code">
            <el-input v-model="from.code" style="width: 80%" placeholder="1-50个字符" />
          </el-form-item>
          <el-form-item label="部门负责人" prop="manager">
            <el-select v-model="from.manager" style="width: 80%" placeholder="请选择">
              <el-option v-for="item in managerList" :key="item.id" :label="item.username" :value="item.username" />
            </el-select>
          </el-form-item>
          <el-form-item label="部门介绍" prop="introduce">
            <el-input v-model="from.introduce" style="width: 80%" placeholder="1-300个字符" type="textarea" />
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addDepartment">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
// 接口方法
import {
  getDepartmentListAPI,
  getDepartmentUserListAPI,
  addDepartmentAPI,
  delDepartmentAPI,
  updataDepartmentAPI,
  getDepartmentAPI
} from '@/api/department'
// 处理树形数据的方法
import transTree from '@/utils/transTree'
export default {
  name: 'Department',
  data() {
    // 验证部门编码重复问题
    const validateCode = (rule, value, callback) => {
      if (this.arr.includes(value)) {
        callback(new Error('部门编码不能重复'))
      }
      callback()
    }
    return {
      // 渲染页面的数据
      list: [],
      // 用来修改树状图提交的数据
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 控制弹窗
      dialogVisible: false,
      // 提交的表单
      from: {
        name: '',
        code: '',
        manager: '',
        introduce: '',
        pid: ''
      },
      // 表单验证
      rules: {
        name: [
          {
            required: true,
            message: '部门名称不能为空',
            trigger: ['blur', 'change']
          },
          {
            min: 1,
            max: 50,
            message: '部门名称要求1-50个字符',
            trigger: ['blur', 'change']
          }
        ],
        code: [
          {
            required: true,
            message: '部门编码不能为空',
            trigger: ['blur', 'change']
          },
          {
            min: 1,
            max: 50,
            message: '部门编码要求1-50个字符',
            trigger: ['blur', 'change']
          },
          { validator: validateCode, trigger: 'blur' }
        ],
        manager: [
          {
            required: true,
            message: '部门负责人不能为空',
            trigger: ['blur', 'change']
          }
        ],
        introduce: [
          {
            required: true,
            message: '部门介绍不能为空',
            trigger: ['blur', 'change']
          },
          {
            min: 1,
            max: 300,
            message: '部门介绍要求1-300个字符',
            trigger: ['blur', 'change']
          }
        ]
      },
      // 部门负责人列表
      managerList: [],
      // 弹出框提示
      title: '',
      // 服务器返回的部门信息
      depts: [],
      // 服务器返回数据的重组数组
      arr: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取部门信息请求
    async getList() {
      const res = await getDepartmentListAPI()
      // 通过方法，把后端返回的平铺的数据，转化成组件需要的树形数据
      this.list = transTree(res.depts)
      // 把服务器返回的数据，放到数组中
      this.depts = res.depts
      // 把数组遍历，把里面的code提取出来，弄一个新数组
      this.arr = this.depts.map(item => item.code)
    },
    // 打开添加部门的弹窗
    openAddDep(id, title) {
      this.title = title
      this.dialogVisible = true
      this.from.pid = id
    },
    // 打开添加部门弹窗，请求部门负责人列表信息
    async openDialog() {
      const res = await getDepartmentUserListAPI()
      this.managerList = res
    },
    // 关闭添加部门弹窗
    closeDialog() {
      this.$refs.addfrom.resetFields()
      this.resFrom()
      this.dialogVisible = false
    },
    // 重置表单
    resFrom() {
      this.from = {
        name: '',
        code: '',
        manager: '',
        introduce: '',
        pid: ''
      }
    },
    // 添加部门
    addDepartment() {
      this.$refs.addfrom.validate(async(valid) => {
        if (!valid) return
        if (this.from.id) {
          await updataDepartmentAPI(this.from)
        } else {
          await addDepartmentAPI(this.from)
        }
        this.$message.success(`${this.from.id ? '编辑' : '添加'}成功`)
        this.getList()
        this.dialogVisible = false
        this.$refs.addfrom.resetFields()
        this.from.id = ''
      })
    },
    // 删除部门(有问题)
    delDep(id) {
      this.$confirm('你确认要进行删除么?', '温馨提示').then(async() => {
        await delDepartmentAPI(id)
        this.getList()
        this.$message.success('删除成功')
      })
    },
    // 打开更新弹窗
    async openUpdataDep(id, title) {
      this.title = title
      const res = await getDepartmentAPI(id)
      this.from = res
      this.dialogVisible = true
    }
  }
}
</script>
